package studio.xiaoyun.common.convert;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import org.springframework.stereotype.Service;

import studio.xiaoyun.common.tool.FileTool;
import studio.xiaoyun.core.BeanFactory;
import studio.xiaoyun.core.Config;
import studio.xiaoyun.core.exception.CoreException;

/**
 * 将一种文件格式转换为其它格式
 */
@Service
public class FileConverter {
	private List<IHtmlConverter> htmlConverterList;
	private List<IPDFConverter> pdfConverterList;

    /**
     * 将文件转换为html文件
     * @param fileName 文件名
     * @return html文件的文件名
     * @throws CoreException 如果转换失败，则抛出异常
     */
    public String toHtml(String fileName) throws CoreException {
    	if(htmlConverterList==null){
    		htmlConverterList = new ArrayList<>();
    		Map<String,IHtmlConverter> map = BeanFactory.getBeansOfType(IHtmlConverter.class);
    		map.forEach((key,value)->htmlConverterList.add(value));
    	}
        File file = new File(fileName);
        if(!file.exists()){
            throw new CoreException("文件不存在");
        }
        String extension = FileTool.getFileExtension(fileName);
        String newFileName = Config.getConvertPath()+ UUID.randomUUID().toString()+File.separator+"index.html";
        Optional<IHtmlConverter> converter = htmlConverterList.stream()
        		.filter(item->item.isSupportedExtensionsForHtmlConverter(extension)).findAny();
        if(!converter.isPresent()){
            throw new CoreException("不支持的文件类型:"+extension);
        }else{
        	converter.get().toHtml(fileName,newFileName);
        }
        return newFileName;
    }

    /**
     * 将文件转换为pdf文件
     * @param fileName 文件名
     * @return pdf文件的文件名
     * @throws CoreException 如果转换失败，则抛出异常
     */
    public String toPdf(String fileName)throws CoreException {
    	if(pdfConverterList==null){
    		pdfConverterList = new ArrayList<>();
    		Map<String,IPDFConverter> map = BeanFactory.getBeansOfType(IPDFConverter.class);
    		map.forEach((key,value)->pdfConverterList.add(value));
    	}
        File file = new File(fileName);
        if(!file.exists()){
            throw new CoreException("文件不存在");
        }
        String extension = FileTool.getFileExtension(fileName);
        String newFileName = Config.getConvertPath()+ "pdf"+File.separator+UUID.randomUUID().toString()+".pdf";
        Optional<IPDFConverter> converter = pdfConverterList.stream()
        		.filter(item->item.isSupportedExtensionsForPDFConverter(extension)).findAny();
        if(!converter.isPresent()){
            throw new CoreException("不支持的文件类型:"+extension);
        }else{
        	converter.get().toPdf(fileName,newFileName);
        }
        return newFileName;
    }

}
